package sb.simple.script;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.datasource.init.DataSourceInitializer;
import org.springframework.jdbc.datasource.init.DatabasePopulator;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;

import javax.sql.DataSource;

/**
 * 项目启动自动执行本地sql脚本
 *
 * 1.编写.sql建表脚本
 * 2.编写.sql插入数据等测试sql脚本
 * 3.编写如当前@Configuration配置类
 *
 * 项目运行后自动执行该类即自动执行.sql脚本
 */
@Configuration
public class CustomizeDataSourceInitializer {

    @Value("classpath:script/schema.sql")
    private Resource sqlScriptSchema;
    @Value("classpath:script/data.sql")
    private Resource sqlScriptData;

    @Bean
    public DataSourceInitializer dataSourceInitializer(final DataSource dataSource) {
        DataSourceInitializer dataSourceInitializer = new DataSourceInitializer();
        dataSourceInitializer.setDataSource(dataSource);
        dataSourceInitializer.setDatabasePopulator(databasePopulator());
        return dataSourceInitializer;
    }

    private DatabasePopulator databasePopulator() {
        ResourceDatabasePopulator resourceDatabasePopulator = new ResourceDatabasePopulator();
        resourceDatabasePopulator.addScript(sqlScriptSchema);
        resourceDatabasePopulator.addScript(sqlScriptData);
        resourceDatabasePopulator.setSeparator(";");//分隔符[默认;]
        return resourceDatabasePopulator;
    }
}

